package com.isp.common.web.excel;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.isp.common.model.excel.EasyExcelSheetModel;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * EasyPoi工具类
 *
 * @author linsy
 * @created: 2024/09/26
 */
public class EasyExcelUtils {


    /**
     * 普通导出
     *
     * @param response 响应
     * @param fileName 文件名
     * @param clazz    导出内容class
     * @param data     导出内容
     * @throws IOException 异常
     */
    public static void download(HttpServletResponse response, String fileName, Class<?> clazz, List<?> data) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet("模板").doWrite(data);
    }

    /**
     * 导出excel（分sheet页）
     *
     * @param outputStream 文件流
     * @param fileName     文件名
     * @param sheetModels  文件内容
     * @throws Exception 异常
     */
    public static void exportExcelModel(ByteArrayOutputStream outputStream, String fileName, List<? extends EasyExcelSheetModel> sheetModels) throws Exception {
        ExcelWriter excelWriter = EasyExcel.write(outputStream).excelType(ExcelTypeEnum.XLSX).build();
        sheetModels.forEach((t) -> {
            SheetWriteHandler sheetWriteHandler = t.getSheetWriteHandler();
            WriteSheet writeSheet;
            if (sheetWriteHandler != null) {
                writeSheet = EasyExcel.writerSheet(t.getSheetName()).head(t.getHead()).registerWriteHandler(sheetWriteHandler).build();
            } else {
                writeSheet = EasyExcel.writerSheet(t.getSheetName()).head(t.getHead()).build();
            }
            excelWriter.write(t.getData(), writeSheet);
        });
        excelWriter.finish();
    }

}
